import { observable, action } from 'mobx';
import { WeaTools } from 'ecCom';
import isEmpty from 'lodash/isEmpty';
import isArray from 'lodash/isArray'
import {validate,getFormParamValue} from '../util'
import * as PublicFunc from '../util/pulic-func';
import {WeaForm} from 'comsMobx';
import {message,Modal} from 'antd';
import * as mobx from 'mobx';
import {i18n} from '../public/i18n';
const toJS = mobx.toJS;
const confirm = Modal.confirm;
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

export class HrmCardInfo {
  loading = false;
  @observable modelItems = []
  @observable infoGroup = []
//   @observable infoGroup2 = []
  @observable imgSrc = null
  @observable sendButtons = []
  @observable accountInfo = []
  @observable showSQR = false
  @observable showBigImg = false
  @observable showAccountInfo = false
  @observable isEditor = false
  @observable buttons = {}
  @observable hideBelongto = true
  @observable rightMenus = []
  @observable conditioninfo = []
  @observable form = new WeaForm()
  @observable QRCodeOptions = {};

  validate;

  hrmId = undefined;

  @action
  updateHideBelongto(bool) {
    this.hideBelongto = bool;
  }

  @action
  updateShowAccountInfo(bool) {
    this.showAccountInfo = bool;
  }

  @action
  updateShowBigImg(bool) {
    this.showBigImg = bool;
  }

  @action
  updateIsEditor(bool) {
    this.isEditor = bool || false;
  }

  @action
  updateShowSQR(bool) {
    this.showSQR = bool;
  }

  format(datas) {
    let infoGroup=[];//信息组
    let imgSrc=null;//人员照片
    let sendButtons= [];
    let accountInfo=[];
    let hrmInfo = [];
    datas && datas.forEach(d=>{
        if(d.id=='item1'){
            hrmInfo = d.items;
        }
        if(d.id=='item2'){
            d.items.forEach(d2=>{
                d2.name == 'resourceimageid' && (imgSrc = d2.value)
                isArray(d2.options) && (sendButtons = d2.options);
                d2.accountinfo && (accountInfo = d2.accountinfo)
            })
        }
        if(d.id != 'item1' && d.id != 'item2' && d.id != 'item3') {
        	infoGroup.push(d);
        }
    })
    this.infoGroup = infoGroup;
    this.imgSrc = imgSrc;
    this.sendButtons = sendButtons;
    this.accountInfo = accountInfo;
  }

  @action
  edit(hrmId){
     this.conditioninfo = [];
    WeaTools.callApi('/api/hrm/resource/getResourceCard', 'GET', {
            operation: 'getResourceBaseView', is_multilang_set:true, viewattr: 2, id: hrmId
    }).then((data)=>{
      this.hasJobTitlesAdd = data.result.hasJobTitlesAdd;

      this.form = new WeaForm();
      this.form.initFormFields(data.result.conditions);
      let resourceimageid = getFormParamValue(data.result.conditions,'resourceimageid');
      this.form.updateFields({
        resourceimageid:{name:'resourceimageid',value:resourceimageid}
      });
      const params = this.form.getFormParams();
      this.conditioninfo = this.processCondition(data.result.conditions) ;
      this.hrmId = data.result.id;
      this.editcontact = data.result.editcontact;
      let accounttype = params.accounttype || '0'
      this.hideBelongto = accounttype == '0'

      this.collectShowFields(data.result.conditions);
    })
    this.isEditor = true;
  }

  @observable jobtitleVisible = false;

  processCondition = (condition) => {
  condition.map(c => c.items.map(item => {
    if (item.domkey[0] === "jobtitle" && this.hasJobTitlesAdd) {
      item.otherParams = {
        hasAddBtn:true,
        addOnClick:()=>{
          this.openJobtitleDialog()
        }
      }
    }
  }));
  return condition;
}

openJobtitleDialog = () => {
  this.jobtitleVisible = true;
}

closeJobtitleDialog = () => {
  this.jobtitleVisible = false;
}

  collectShowFields = (conditions) => {
    this.showFormFields = [];
    conditions.map(c => c.items.map(item => {
      const {otherParams,domkey} = item;
      if (
        !otherParams || 
       (otherParams && !otherParams.hide)
      ) {
       this.showFormFields.push(domkey[0]);
      }
    }));
  }

  saveEditCard(cb){
    if(this.loading)
      return;
    this.loading = true;
    let __this = this;
    const fieldParams = this.form.getFormParams();
    const conditioninfo = this.conditioninfo;
    const editcontact = this.editcontact;
    const hrmId = this.hrmId;
    const lastname = fieldParams.lastname||'';
    const workcode = fieldParams.workcode||'';
    const managerid = fieldParams.managerid||'';
    const accounttype = fieldParams.accounttype||'';
    const belongto = fieldParams.belongto||'';
    const email = fieldParams.email||'';
    const mobilecall = fieldParams.mobilecall||'';
    const mobile = fieldParams.mobile||'';
    if(this.showFormFields.includes('email') && !PublicFunc.chkMail(email)) {
      this.loading = false;
      return false;
    }
    if (validate(conditioninfo, fieldParams)){
        //选次账号后，必须选主账号
        if(this.showFormFields.includes('accounttype') && accounttype && accounttype==1){
            if(!belongto || belongto==''){
                message.warning(getLabel('386411',"主账号未填写"));
                __this.loading = false;
                return;
            }
        }
        if(this.showFormFields.includes('managerid') && managerid=='' && (!editcontact || editcontact=='')){
            confirm({
                title: i18n.confirm.systemhints(),
                content: getLabel('16072',"此员工还没有输入直接上级，确定不输入吗？"),
                onOk(){
                    WeaTools.callApi('/api/hrm/resource/hrmResourceCheck','GET',
                    {...{id: hrmId,lastname,workcode,managerid,mobilecall,mobile}}).
                    then(data=>{
                        if (data.status == '-1') {
                            if(data.messagetype=='confirm'){
                                confirm({
                                    title:i18n.confirm.systemhints(),
                                    content: data.message,
                                    onOk(){
                                        __this.doSave(cb);
                                    },
                                    onCancel(){
                                      __this.loading = false;
                                    },
                                });
                            }else{
                                message.warning(data.message);
                                __this.loading = false;
                            }
                        }else{
                            __this.doSave(cb);
                        }
                    }, error=> {
                        message.warning(error.message);
                        __this.loading = false;
                    })
                },
                onCancel(){
                  __this.loading = false;
                },
              });
        }else{
          const params = {
            id: hrmId
          };

          ['lastname','workcode','managerid','mobile','mobilecall'].forEach(val => {
            if(this.showFormFields.includes(val)){
              Object.assign(params,{
                [val]:fieldParams[val]
              });
            }
          })

            WeaTools.callApi('/api/hrm/resource/hrmResourceCheck','GET',params).
            then(data=>{
                if (data.status == '-1') {
                    if(data.messagetype=='confirm'){
                        confirm({
                            title: i18n.confirm.systemhints(),
                            content: data.message,
                            onOk(){
                                __this.doSave(cb);
                            },
                            onCancel(){
                              __this.loading = false;
                            },
                        });
                    }else{
                        message.warning(data.message);
                        __this.loading = false;
                    }
                }else{
                    __this.doSave(cb);
                }
            }, error=> {
                message.warning(error.message);
                __this.loading = false;
            })
        }

    }else
      this.loading = false;
  }

  doSave(cb){
    let __this = this;
    const fieldParams = this.form.getFormParams();
    const conditioninfo = this.conditioninfo;
    const editcontact = this.editcontact;
    const hrmId = this.hrmId;
    WeaTools.callApi('/api/hrm/resource/editResource','POST',
    {...{operation:'editresourcebasicinfo', id: hrmId, editcontact}, ...fieldParams}).
    then(data=>{
        if (data.status == '1') {
            message.success(i18n.message.saveSuccess());
            this.isEditor = false;
            this.getData(hrmId);
            cb();
        } else {
            message.warning(data.message);
        }
        this.loading = false;
    }, error=> {
        message.warning(error.message);
        this.loading = false;
    })
  }

  @action
  getRightMenu(hrmId) {
    WeaTools.callApi('/api/hrm/resource/getRightMenu','GET',{id:hrmId}).then(data => {
      this.rightMenus = data.rightMenus;
    })
  }

  @action
  qrcode(hrmId) {
    WeaTools.callApi('/api/hrm/resource/getQRCode','GET',{id:hrmId}).then(obj=>{
      this.QRCodeOptions = obj.options;
    }).catch(err=>{
      message.error(err);
    })
  }

  @action
  getData(hrmId) {
    this.hideBelongto = true;
    Promise.all([
      WeaTools.callApi('/api/hrm/resource/getResourceCard','GET',
        {operation:'getResourceBaseView',id:hrmId, noLoadData: 1})
      ,
      WeaTools.callApi('/api/hrm/resource/getResourceCard','GET',
        {operation:'getResourceBaseView',id:hrmId, cmd:'getResourceBaseData', noLoadData: 1})
      ,
      WeaTools.callApi('/api/hrm/resource/getHrmResourceItem','GET',{id:hrmId,  noLoadData: 1})
    ]).then(res=> {
      this.format(res[0].result);
      this.buttons = res[0].buttons;
      this.modelItems = res[2];
      WeaTools.callApi('/api/hrm/resource/getResourceCard','GET',{operation:'getResourceBaseView',id:hrmId}).then(datas=>{
        this.format(datas.result);
        this.validate = datas.validate;
      }),
      WeaTools.callApi('/api/hrm/resource/getResourceCard','GET',{operation:'getResourceBaseView',id:hrmId,cmd:'getResourceBaseData'}).then(datas=>{
        this.format(datas.result);
      })
       WeaTools.callApi('/api/hrm/resource/getHrmResourceItem','GET',{id:hrmId}).then(datas=>{
        this.modelItems = datas;
      })
      this.qrcode(hrmId);
    })
  }
}